package my.mall.common.config

import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.util.StringUtils
import java.util.concurrent.SynchronousQueue
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit

@Configuration
open class ThreadPoolConfig {

    @Bean
    open fun threadPoolExecutor(config: ThreadPoolConfigProperties?): ThreadPoolExecutor {
        var coreSize = 0
        var maxSize = 2000
        var keepAliveTime = 120
        var threadPoolNamePrefix: String? = "mall-"
        if (config != null) {
            if (config.coreSize != null) {
                coreSize = config.coreSize!!
            }
            if (config.maxSize != null) {
                maxSize = config.maxSize!!
            }
            if (config.keepAliveTime != null) {
                keepAliveTime = config.keepAliveTime!!
            }
            if (StringUtils.hasLength(config.threadPoolName)) {
                threadPoolNamePrefix = config.threadPoolName
            }
        }
        return ThreadPoolExecutor(
            coreSize, maxSize,
            keepAliveTime.toLong(), TimeUnit.SECONDS,
            SynchronousQueue(),
            Thread.ofVirtual().name(threadPoolNamePrefix, 0).factory(),
            ThreadPoolExecutor.CallerRunsPolicy()
        )
    }
}
